<template>
  <div id="contestProblemView">
    <a-row :gutter="16">
      <!-- 左侧：题目详情 -->
      <a-col :span="12">
        <a-card :bordered="false" class="problem-card">
          <template #title>
            <div class="problem-header">
              <div>
                <span class="problem-number">{{ problemIndex }}</span>
                {{ problem.title }}
              </div>
              <a-space>
                <a-tag :color="getDifficultyColor(problem.difficulty)">
                  {{ getDifficultyText(problem.difficulty) }}
                </a-tag>
                <a-tag color="blue">
                  已提交: {{ problem.submitNum || 0 }}
                </a-tag>
                <a-tag color="green">
                  已通过: {{ problem.acceptedNum || 0 }}
                </a-tag>
              </a-space>
            </div>
          </template>

          <a-tabs>
            <a-tab-pane key="description" tab="题目描述">
              <div class="problem-content">
                <div class="problem-section">
                  <h3>题目描述</h3>
                  <div>{{ problem.description }}</div>
                </div>
                <div class="problem-section">
                  <h3>输入描述</h3>
                  <div>{{ problem.input }}</div>
                </div>
                <div class="problem-section">
                  <h3>输出描述</h3>
                  <div>{{ problem.output }}</div>
                </div>
                <div class="problem-section">
                  <h3>示例</h3>
                  <a-card
                    v-for="(example, index) in problem.examples || []"
                    :key="index"
                    :bordered="false"
                    class="example-card"
                  >
                    <a-row :gutter="16">
                      <a-col :span="12">
                        <div class="example-title">输入 {{ index + 1 }}</div>
                        <pre class="example-content">{{ example.input }}</pre>
                      </a-col>
                      <a-col :span="12">
                        <div class="example-title">输出 {{ index + 1 }}</div>
                        <pre class="example-content">{{ example.output }}</pre>
                      </a-col>
                    </a-row>
                  </a-card>
                </div>
                <div class="problem-section" v-if="problem.hint">
                  <h3>提示</h3>
                  <div>{{ problem.hint }}</div>
                </div>
                <div class="problem-section">
                  <h3>限制</h3>
                  <div>
                    <p>
                      时间限制: {{ problem.judgeConfig?.timeLimit || 1000 }} ms
                    </p>
                    <p>
                      内存限制: {{ problem.judgeConfig?.memoryLimit || 128 }} MB
                    </p>
                    <p>
                      代码长度限制:
                      {{ problem.judgeConfig?.stackLimit || 8 }} MB
                    </p>
                  </div>
                </div>
                <div
                  class="problem-section"
                  v-if="problem.tags && problem.tags.length > 0"
                >
                  <h3>标签</h3>
                  <div>
                    <a-tag v-for="tag in problem.tags" :key="tag" color="blue">
                      {{ tag }}
                    </a-tag>
                  </div>
                </div>
              </div>
            </a-tab-pane>
            <a-tab-pane key="submissions" tab="我的提交">
              <a-table
                :columns="submissionColumns"
                :data-source="mySubmissions"
                :loading="submissionsLoading"
                :pagination="false"
                size="small"
              >
                <template #bodyCell="{ column, record }">
                  <template v-if="column.dataIndex === 'status'">
                    <a-tag :color="getStatusColor(record.judgeInfo?.status)">
                      {{ getStatusText(record.judgeInfo?.status) }}
                    </a-tag>
                  </template>
                  <template v-if="column.dataIndex === 'language'">
                    {{ getLanguageText(record.language) }}
                  </template>
                  <template v-if="column.dataIndex === 'judgeInfo'">
                    <span v-if="record.judgeInfo?.message">
                      {{ record.judgeInfo.message }}
                    </span>
                    <span v-else-if="record.judgeInfo?.status === 2">
                      Time: {{ record.judgeInfo?.time || 0 }}ms | Memory:
                      {{ (record.judgeInfo?.memory || 0) / 1024 / 1024 }}MB
                    </span>
                  </template>
                  <template v-if="column.dataIndex === 'createTime'">
                    {{ formatDate(record.createTime) }}
                  </template>
                </template>
              </a-table>
            </a-tab-pane>
          </a-tabs>
        </a-card>
      </a-col>

      <!-- 右侧：代码编辑器和提交 -->
      <a-col :span="12">
        <a-card :bordered="false" class="code-card">
          <template #title>
            <div class="code-header">
              <span>代码编辑器</span>
              <a-space>
                <a-select
                  v-model:value="language"
                  style="width: 120px"
                  @change="handleLanguageChange"
                >
                  <a-select-option value="java">Java</a-select-option>
                  <a-select-option value="cpp">C++</a-select-option>
                  <a-select-option value="python">Python</a-select-option>
                </a-select>
                <a-button
                  type="primary"
                  @click="submitCode"
                  :loading="submitting"
                >
                  提交
                </a-button>
              </a-space>
            </div>
          </template>

          <div class="code-editor-container">
            <code-editor
              :value="code"
              :language="language"
              :theme="'vs-dark'"
              @change="handleCodeChange"
            />
          </div>

          <!-- 运行结果 -->
          <div v-if="currentSubmission" class="submission-result">
            <a-divider>运行结果</a-divider>
            <a-row>
              <a-col :span="8">
                <div class="result-item">
                  <div class="result-label">状态</div>
                  <div class="result-value">
                    <a-tag
                      :color="
                        getStatusColor(currentSubmission.judgeInfo?.status)
                      "
                    >
                      {{ getStatusText(currentSubmission.judgeInfo?.status) }}
                    </a-tag>
                  </div>
                </div>
              </a-col>
              <a-col :span="8">
                <div class="result-item">
                  <div class="result-label">用时</div>
                  <div class="result-value">
                    {{ currentSubmission.judgeInfo?.time || 0 }} ms
                  </div>
                </div>
              </a-col>
              <a-col :span="8">
                <div class="result-item">
                  <div class="result-label">内存</div>
                  <div class="result-value">
                    {{
                      (currentSubmission.judgeInfo?.memory || 0) / 1024 / 1024
                    }}
                    MB
                  </div>
                </div>
              </a-col>
            </a-row>
            <div
              v-if="currentSubmission.judgeInfo?.message"
              class="result-message"
            >
              {{ currentSubmission.judgeInfo.message }}
            </div>
          </div>
        </a-card>
      </a-col>
    </a-row>

    <!-- 问题导航栏 -->
    <a-affix :offset-bottom="20">
      <div class="problem-navigator">
        <a-row justify="space-between" align="middle">
          <a-col>
            <a-space>
              <a-button
                @click="previousProblem"
                :disabled="!hasPreviousProblem"
              >
                上一题
              </a-button>
              <a-dropdown :trigger="['click']">
                <a-button> {{ problemIndex }} <down-outlined /> </a-button>
                <template #overlay>
                  <a-menu>
                    <a-menu-item
                      v-for="(p, index) in contestProblems"
                      :key="p.id"
                      @click="navigateToProblem(p.id)"
                    >
                      {{ String.fromCharCode(65 + index) }} - {{ p.title }}
                    </a-menu-item>
                  </a-menu>
                </template>
              </a-dropdown>
              <a-button @click="nextProblem" :disabled="!hasNextProblem">
                下一题
              </a-button>
            </a-space>
          </a-col>
          <a-col>
            <a-space>
              <a-statistic
                title="剩余时间"
                :value="remainingTime"
                style="margin-right: 16px"
              />
              <a-button type="primary" @click="backToContest">
                返回竞赛
              </a-button>
            </a-space>
          </a-col>
        </a-row>
      </div>
    </a-affix>
  </div>
</template>

<script setup lang="ts">
/* eslint-disable */
import { onMounted, onUnmounted, ref, reactive, computed } from "vue";
import { useRoute, useRouter } from "vue-router";
import { message } from "ant-design-vue";
import { DownOutlined } from "@ant-design/icons-vue";
import CodeEditor from "@/components/CodeEditor.vue";
import { ContestControllerService } from "../../../generated/services/ContestControllerService";
import { ContestSubmitControllerService } from "../../../generated/services/ContestSubmitControllerService";
import { QuestionControllerService } from "../../../generated/services/QuestionControllerService";
import { formatDate } from "@/utils/dateUtil";

// 初始化数据
const route = useRoute();
const router = useRouter();
const contestId = computed(() => Number(route.params.contestId));
const problemId = computed(() => Number(route.params.problemId));

// 竞赛信息
const contestInfo = ref({
  id: 0,
  title: "",
  startTime: "",
  duration: 120,
  status: 0,
});

// 题目信息
const problem = ref({
  id: 0,
  title: "",
  description: "",
  input: "",
  output: "",
  examples: [],
  tags: [],
  difficulty: 0,
  judgeConfig: {
    timeLimit: 1000,
    memoryLimit: 128,
    stackLimit: 8,
  },
  submitNum: 0,
  acceptedNum: 0,
});

// 竞赛题目列表
const contestProblems = ref([]);
const currentProblemIndex = ref(0);
const problemIndex = computed(() => {
  return String.fromCharCode(65 + currentProblemIndex.value);
});

// 导航按钮状态
const hasPreviousProblem = computed(() => currentProblemIndex.value > 0);
const hasNextProblem = computed(
  () => currentProblemIndex.value < contestProblems.value.length - 1
);

// 代码编辑器
const language = ref("java");
const languageTemplates = {
  java: `import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        // 在这里编写你的代码
        
        scanner.close();
    }
}`,
  cpp: `#include <iostream>
using namespace std;

int main() {
    // 在这里编写你的代码
    
    return 0;
}`,
  python: `# 在这里编写你的代码

`,
};
const code = ref(languageTemplates.java);

// 提交相关
const submitting = ref(false);
const submissionsLoading = ref(false);
const mySubmissions = ref([]);
const currentSubmission = ref(null);
const submissionColumns = [
  {
    title: "提交时间",
    dataIndex: "createTime",
    width: 180,
  },
  {
    title: "语言",
    dataIndex: "language",
    width: 100,
  },
  {
    title: "状态",
    dataIndex: "status",
    width: 120,
  },
  {
    title: "结果信息",
    dataIndex: "judgeInfo",
  },
];

// 倒计时
const remainingTime = ref("");
let timer = null;

// 获取竞赛信息
const getContestInfo = async () => {
  try {
    const res = await ContestControllerService.getContestByIdUsingGet(
      contestId.value
    );
    if (res.code === 0) {
      contestInfo.value = res.data;

      // 设置倒计时
      updateRemainingTime();
      timer = setInterval(() => {
        updateRemainingTime();
      }, 1000);

      // 加载竞赛题目列表
      if (res.data.questionList && res.data.questionList.length > 0) {
        contestProblems.value = res.data.questionList;
        // 找出当前题目的索引
        currentProblemIndex.value = contestProblems.value.findIndex(
          (p) => p.id === problemId.value
        );
      }
    } else {
      message.error("获取竞赛信息失败");
    }
  } catch (error) {
    console.error("获取竞赛信息异常", error);
    message.error("获取竞赛信息异常");
  }
};

// 更新倒计时
const updateRemainingTime = () => {
  const now = new Date().getTime();
  const startTime = new Date(contestInfo.value.startTime).getTime();
  const endTime = startTime + contestInfo.value.duration * 60 * 1000;
  const diff = endTime - now;

  if (diff <= 0) {
    clearInterval(timer);
    remainingTime.value = "竞赛已结束";
    message.warning("竞赛已结束");
    return;
  }

  // 计算时分秒
  const hours = Math.floor(diff / (1000 * 60 * 60));
  const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
  const seconds = Math.floor((diff % (1000 * 60)) / 1000);

  remainingTime.value = `${hours}小时 ${minutes}分 ${seconds}秒`;
};

// 获取题目详情
const getProblemDetail = async () => {
  try {
    const res = await QuestionControllerService.getQuestionByIdUsingGet(
      problemId.value
    );
    if (res.code === 0) {
      problem.value = res.data;
    } else {
      message.error("获取题目详情失败");
    }
  } catch (error) {
    console.error("获取题目详情异常", error);
    message.error("获取题目详情异常");
  }
};

// 获取我的提交记录
const getMySubmissions = async () => {
  try {
    submissionsLoading.value = true;

    // 获取竞赛中对该题的提交
    const res =
      await ContestSubmitControllerService.getUserQuestionAttemptsUsingGet(
        contestId.value,
        problemId.value
      );
    if (res.code === 0) {
      mySubmissions.value = res.data || [];

      // 如果有提交记录，显示最新一条
      if (mySubmissions.value.length > 0) {
        currentSubmission.value = mySubmissions.value[0];
      }
    } else {
      message.error("获取提交记录失败");
    }
  } catch (error) {
    console.error("获取提交记录异常", error);
    message.error("获取提交记录异常");
  } finally {
    submissionsLoading.value = false;
  }
};

// 处理语言变化
const handleLanguageChange = (value) => {
  // 如果当前代码是默认模板或为空，则切换为新语言的默认模板
  if (
    code.value === languageTemplates.java ||
    code.value === languageTemplates.cpp ||
    code.value === languageTemplates.python ||
    code.value.trim() === ""
  ) {
    code.value = languageTemplates[value];
  }
};

// 处理代码变化
const handleCodeChange = (value) => {
  code.value = value;
};

// 提交代码
const submitCode = async () => {
  try {
    submitting.value = true;

    // 转换语言为枚举值
    const languageMap = {
      java: "JAVA",
      cpp: "CPP",
      python: "PYTHON",
    };

    const res = await ContestSubmitControllerService.doContestSubmitUsingPost(
      {
        language: languageMap[language.value],
        code: code.value,
        questionId: problemId.value,
      },
      contestId.value
    );

    if (res.code === 0) {
      message.success("提交成功");

      // 定时查询提交结果
      checkSubmitResult(res.data);
    } else {
      message.error(res.message || "提交失败");
    }
  } catch (error) {
    console.error("提交代码异常", error);
    message.error("提交代码失败");
  } finally {
    submitting.value = false;
  }
};

// 检查提交结果
const checkSubmitResult = async (submitId) => {
  try {
    // 等待1秒后查询
    setTimeout(async () => {
      // 这里假设有一个根据ID查询提交详情的接口
      // 实际应根据后端API调整
      getMySubmissions();
    }, 1000);
  } catch (error) {
    console.error("查询提交结果异常", error);
  }
};

// 获取题目难度文本
const getDifficultyText = (difficulty) => {
  const difficultyMap = { 0: "简单", 1: "中等", 2: "困难" };
  return difficultyMap[difficulty] || "未知";
};

// 获取题目难度颜色
const getDifficultyColor = (difficulty) => {
  const colorMap = { 0: "green", 1: "orange", 2: "red" };
  return colorMap[difficulty] || "default";
};

// 获取提交状态文本
const getStatusText = (status) => {
  const statusMap = {
    0: "待判题",
    1: "判题中",
    2: "成功",
    3: "失败",
  };
  return statusMap[status] || "未知";
};

// 获取提交状态颜色
const getStatusColor = (status) => {
  const colorMap = {
    0: "blue",
    1: "orange",
    2: "green",
    3: "red",
  };
  return colorMap[status] || "default";
};

// 获取语言文本
const getLanguageText = (language) => {
  const languageMap = {
    JAVA: "Java",
    CPP: "C++",
    PYTHON: "Python",
  };
  return languageMap[language] || language;
};

// 上一题
const previousProblem = () => {
  if (hasPreviousProblem.value) {
    const prevProblem = contestProblems.value[currentProblemIndex.value - 1];
    navigateToProblem(prevProblem.id);
  }
};

// 下一题
const nextProblem = () => {
  if (hasNextProblem.value) {
    const nextProblem = contestProblems.value[currentProblemIndex.value + 1];
    navigateToProblem(nextProblem.id);
  }
};

// 导航到指定题目
const navigateToProblem = (id) => {
  router.push(`/contest/${contestId.value}/problem/${id}`);
};

// 返回竞赛页面
const backToContest = () => {
  router.push(`/contest/${contestId.value}`);
};

// 生命周期钩子
onMounted(() => {
  getContestInfo();
  getProblemDetail();
  getMySubmissions();
});

onUnmounted(() => {
  // 清除定时器
  if (timer) {
    clearInterval(timer);
  }
});
</script>

<style scoped>
#contestProblemView {
  padding: 24px;
}

.problem-card,
.code-card {
  margin-bottom: 24px;
  height: calc(100vh - 170px);
  overflow-y: auto;
}

.problem-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.problem-number {
  display: inline-block;
  width: 30px;
  height: 30px;
  line-height: 30px;
  text-align: center;
  background-color: #1890ff;
  color: white;
  border-radius: 50%;
  margin-right: 8px;
}

.problem-content {
  padding: 16px 0;
}

.problem-section {
  margin-bottom: 24px;
}

.problem-section h3 {
  margin-bottom: 16px;
  font-weight: 500;
}

.example-card {
  margin-bottom: 16px;
  background-color: #f5f5f5;
}

.example-title {
  font-weight: 500;
  margin-bottom: 8px;
}

.example-content {
  background-color: white;
  padding: 8px;
  border-radius: 4px;
  overflow-x: auto;
}

.code-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.code-editor-container {
  height: calc(100% - 180px);
  margin-bottom: 16px;
}

.submission-result {
  margin-top: 16px;
}

.result-item {
  padding: 8px;
}

.result-label {
  color: rgba(0, 0, 0, 0.45);
  font-size: 14px;
}

.result-value {
  font-size: 16px;
  margin-top: 4px;
}

.result-message {
  margin-top: 16px;
  padding: 16px;
  background-color: #f5f5f5;
  border-radius: 4px;
  white-space: pre-wrap;
}

.problem-navigator {
  padding: 16px;
  background-color: white;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}
</style>
